import { defineStore } from "pinia";
import {
  type userType,
  store,
  router,
  resetRouter,
  routerArrays,
  storageLocal
} from "../utils";
import {
  type UserLoginDTO,
  type UserLoginVO,
  type UserVO,
  login,
  logout,
  getUserInfo
} from "@/api/user";
import { useMultiTagsStoreHook } from "./multiTags";
import { type DataInfo, setToken, removeToken, userKey } from "@/utils/auth";
import { log } from "console";

export const useUserStore = defineStore("pure-user", {
  state: (): userType => ({
    avatar: "",
    username: "",
    nickname: "",
    roles: [],
    permissions: [],
    isRemembered: false,
    loginDay: 7
  }),
  actions: {
    /** 登录 */
    async loginByUsername(data: UserLoginDTO) {
      return new Promise<UserLoginVO>((resolve, reject) => {
        login(data)
          .then(response => {
            const tokenData = {
              accessToken: response.token,
              expires: new Date(Date.now() + 24 * 60 * 60 * 1000).getTime(),
              refreshToken: response.token,
              username: response.username,
              avatar: response.avatar,
              roles: ["user"],
              permissions: ["*:*:*"]
            };
            setToken(tokenData);
            this.username = response.username;
            this.avatar = response.avatar;
            this.roles = ["user"];
            this.permissions = ["*:*:*"];
            resolve(response);
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    /** 微信登录 */
    async loginByWechat(data: { code: string }) {
      return new Promise<void>((resolve, reject) => {
        // 调用后端微信登录接口
        http.request<any, any>("post", "/auth/wechat/login", { data })
          .then(res => {
            if (res.success) {
              // 设置token等信息
              setToken(res.data.accessToken);
              // 设置用户信息
              this.username = res.data.username;
              this.roles = res.data.roles || [];
              resolve();
            } else {
              reject(new Error(res.message));
            }
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    /** 登出 */
    async logOut() {
      try {
        await logout();
      } catch (error) {
        console.error("登出失败:", error);
      } finally {
        this.username = "";
        this.avatar = "";
        this.roles = [];
        this.permissions = [];
        removeToken();
        useMultiTagsStoreHook().handleTags("equal", [...routerArrays]);
        resetRouter();
        router.push("/login");
      }
    },
    /** 获取用户信息 */
    async getUserInfo() {
      return new Promise<UserVO>((resolve, reject) => {
        getUserInfo()
          .then(response => {
            this.username = response.username;
            this.avatar = response.avatar;
            this.roles = ["user"];
            this.permissions = ["*:*:*"];
            resolve(response);
          })
          .catch(error => {
            reject(error);
          });
      });
    }
  }
});

export function useUserStoreHook() {
  return useUserStore(store);
}
